import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './addbill.module.css';
import Input from "@/components/Input";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Toast } from "antd-mobile";
import { useHistory } from "react-router-dom/cjs/react-router-dom";
import { saveEvent } from "@/store/actions/saveEvent";
import { LangThai } from "@/utils/langThai";
import NavigateBar from "@/components/NavigateBar";
import { addBill } from "@/store/actions/user";

/**
 * 登录页
 */
export default function AddBill() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);

    // 类型
    const [curType, setCurType] = useState("支出")

    // 文案翻译
    const [curLang, setCurLang] = useState(LangThai);

    //router
    const history = useHistory()

    // const location = useLocation()

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //清空登录信息
    useEffect(() => {
        //打点
        doHitEvent("LOGIN_START")

        return () => {
            //打点
            doHitEvent("LOGIN_END")
        }
    }, [])

    // Formik 表单对象
    const form = useFormik({
        //设置表单初始值
        initialValues: {
            type: '支出',
            amount: '',
            tag: '',
            detail: ''
        },

        //提交
        onSubmit: values => {
            console.log(values)

            //提交保存
            onDoSaveBill()
        },

        //校验
        validate(values) {
            const errors = {}
            // 非空
            if (!values.amount || values.amount === '') {
                errors.mobile = '请输入正确的金额';
            }

            if (!values.tag || values.tag === '') {
                errors.name = '请输入正确的标签';
            }

            if (!values.detail || values.detail === '') {
                errors.name = '请输入正确的备注';
            }

            return errors
        }
    });

    //请求 新增账单 接口
    const doSaveBill = async (type, amount, tag, detail, password) => {
        console.log("doSaveBill: " + type + " , " + amount + " , " + tag + " , " + detail);

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = addBill(type, amount, tag, detail, onDoSaveBillCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 点击 nav back
    const onHandleNavBackClick = () => {
        history.goBack();
    };

    // 点击 类型
    const onTypeClick = (type) => {
        // form.values.type = type || "支出";
        // setCurType(form.values.type);

        let newValues = { ...form.values };
        newValues.type = type || "支出";

        form.setValues(newValues);

    };

    // 新增账单 返回
    const onDoSaveBillCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('新增账单 返回: ' + success);

        // 刷新列表
        setCurType('支出');
        form.resetForm();

        // 提示
        Toast.show('新增成功');
    };

    //点击 保存
    const onDoSaveBill = async () => {
        try {
            //打点
            doHitEvent("LOGIN_COMMIT_CLICK")

            let inputResult = isInputCorrect();
            console.log(inputResult);
            if (!inputResult) return;

            // 增加
            doSaveBill(form.values.type, inputResult.amount, inputResult.tag, inputResult.detail);

        } catch (e) {
            console.log(e)
        }
    }

    // 判断输入是否合法
    const isInputCorrect = () => {
        //验证
        let amount = form.values.amount;

        //验证
        let tag = form.values.tag;

        //验证
        let detail = form.values.detail;

        console.log('a: ' + amount + ", t:" + tag + ", d:" + detail);


        if (!amount || (amount.length <= 0)) {
            return null;
        }

        if (!tag || (tag.length <= 0)) {
            return null;
        }

        if (!detail || (detail.length <= 0)) {
            return null;
        }

        return { amount: amount, tag: tag, detail: detail };
    };

    return (
        <div className='pageRoot pageBackgroundColorGray'>
            <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskVisible(true) }} onGoBack={onHandleNavBackClick}>增加</NavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumn pageContentPaddingHorizontal10px">

                <form className="pageContentColumn pageContentPadding16px pageMarginTop10px pageContentBorderRadius16px pageBackgroundColorWhite" onSubmit={form.handleSubmit}>

                    {/* 类型选择框 */}
                    <div className={`${styles.addBillverifyInput} pageMarginTopZero`}>
                        <div className={styles.addBillMenuTitle}>类型</div>
                        <div className={styles.addBillMenuRow}>
                            <div className={`${form.values.type === "支出" ? styles.addBillTypeSelected : styles.addBillTypeUnSelect}`} onClick={() => { onTypeClick("支出") }}>支出</div>
                            <div className={`${form.values.type === "支出" ? styles.addBillTypeUnSelect : styles.addBillTypeSelected}`} onClick={() => { onTypeClick("收入") }}>收入</div>
                        </div>
                    </div>
                    {form.errors.type && form.touched.type && (
                        <div className={styles.addBillValidate}>{form.errors.type}</div>
                    )}

                    {/* 金额输入框 */}
                    <div className={styles.addBillverifyInput}>
                        <Input
                            id="amount"
                            title='金额'
                            name="amount"
                            placeholder='请输入'
                            type="number"
                            value={form.values.amount}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.amount && form.touched.amount && (
                        <div className={styles.addBillValidate}>{form.errors.amount}</div>
                    )}

                    {/* 标签框 */}
                    <div className={styles.addBillverifyInput}>
                        <Input
                            id="tag"
                            title='标签'
                            name="tag"
                            placeholder='请输入'
                            type="text"
                            value={form.values.tag}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.tag && form.touched.tag && (
                        <div className={styles.addBillValidate}>{form.errors.tag}</div>
                    )}

                    {/* 备注输入框 */}
                    <div className={styles.addBillverifyInput}>
                        <Input
                            id="detail"
                            title='备注'
                            name="detail"
                            placeholder='请输入'
                            type="text"
                            value={form.values.detail}
                            onBlur={form.handleBlur}
                            onChange={form.handleChange}
                            autoComplete="off" />
                    </div>
                    {form.errors.detail && form.touched.detail && (
                        <div className={styles.addBillValidate}>{form.errors.detail}</div>
                    )}
                </form>

                <div className={`pageBtnSubmit pageMarginTop26px ${(form.isValid && form.dirty) ? '' : "disabled"}`} onClick={form.handleSubmit} >保存</div>

                {/* 底部 margin */}
                <div className="pageBottomEdge"> </div>

                {/* load mask */}
                <Mask visible={maskVisible} opacity={0.1}
                    onMaskClick={() => { }}>
                    <div className="pageLoadingOverlayContent">
                        <span style={{ fontSize: 24, color: '#3498DB' }} >
                            <DotLoading color="currentColor" />
                        </span>
                    </div>
                </Mask>
            </div>
        </div >
    )
}